package config

import (
	"log"

	"github.com/cyfqyb/fiber_demo/global"
	"github.com/gofiber/fiber/v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func init() {
	RegisterConfigsInitializer(InitDb)
}
func InitDb(app *fiber.App) {
	dbConfig := global.Config.GetStringMapString("db")
	if dbConfig == nil {
		log.Fatal("数据库配置不存在")
	}
	username := dbConfig["username"]
	password := dbConfig["password"]
	host := dbConfig["host"]
	port := dbConfig["port"]
	dbName := dbConfig["dbname"]
	db, err := gorm.Open(mysql.Open(username+":"+password+"@tcp("+host+":"+port+")/"+dbName+"?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁用表名复数
		},
	})
	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}
	global.Db = db
	log.Printf("数据库连接成功")
}
